#include "maininterfacewidget.h"
#include "ui_maininterfacewidget.h"
#include "user.h"
#include "addfriendsender.h"
#include "addfriendreceiver.h"
#include "addfriendsearch.h"
#include "friendlist.h"

void MainInterfaceWidget::closeEvent(QCloseEvent *)
{
    emit this->closeMainInterfaceWidget();
}

void MainInterfaceWidget::keyPressEvent(QKeyEvent *event)
{
    if (event->key() == Qt::Key_Return || event->key() == Qt::Key_Enter) {
        on_btn_send_main_clicked(); // 模拟发送按钮被点击的事件
    }
}

MainInterfaceWidget::MainInterfaceWidget(QWidget *parent, user userSelf, QString friendName, int friendId, QWebSocket* socket)
    : QWidget(parent)
    , ui(new Ui::MainInterfaceWidget)
{
    ui->setupUi(this);
    //connect()
    //qDebug() << "userSelf:" << userSelf.getUserName();
    //websocket传输代码
    this->userSelf = userSelf;
    this->userSelf.setUserName(userSelf.getUserName());
    //qDebug() << "userSelf username:" << this->userSelf.name;
    this->friendName = friendName;
    this->friendId = friendId;
    //qDebug()<<this->friendId;
    //QUrl url("ws://localhost:19999/slimarveous/ws");

    this->socket=socket;


    for(int i = 0; i < messageQueue.size(); i++)
    {
        //拉取的信息需要和打开的好友窗口是同一人
        if((messageQueue[i].receiverId == this->userSelf.getUserId().toInt())&&(messageQueue[i].senderId == this->friendId))
        {
            ui->dialogTextBrowser->append(messageQueue[i].getTimeAndSender());
            ui->dialogTextBrowser->append(messageQueue[i].getMessageContent());//对话框中添加信息
            //对话双方均在线直接显示
        }
        //拉取的信息是自己发的消息且消息接收者是窗口打开的好友
        if((messageQueue[i].receiverId == this->friendId)&&(messageQueue[i].senderId == this->userSelf.getUserId().toInt()))
        {
            ui->dialogTextBrowser->append(messageQueue[i].messageTime+" me:");
            ui->dialogTextBrowser->append(messageQueue[i].getMessageContent());//对话框中添加信息
            //对话双方均在线直接显示
        }
    }
    QObject::connect(socket, &QWebSocket::textMessageReceived, [=](const QString &message)
    {
        //qDebug() << "Received message:" << message;
        //接收信息
        QJsonDocument doc = QJsonDocument::fromJson(message.toUtf8());
        //doc转换成json
        QJsonObject obj = doc.object();
        //分析接收到的服务器信息类型
        QString type = obj.value("type").toString();//传到服务器后端的类型type参数
         qDebug() << obj ;
        //类型为chat
        if (type == "chat")
        {
            //messageJson.append(obj);
            //messageReceiver.append(userSelf.name);//插入信息接收者容器
            QVariantMap messageMap = obj.toVariantMap();
            QMap senderMap = messageMap.value("sender").toMap();
            QVariant senderName = senderMap.value("username");
            QVariant senderId = senderMap.value("id");
            QString receivedContent = obj.value("content").toString();
            QString receivedTime = obj.value("time").toString();
            //接收到信息
            Message chatMessage{this->userSelf.getUserName(), this->userSelf.getUserId().toInt(),receivedTime, senderName.toString(), senderId.toInt(), receivedContent};
            //messageQueue.append(chatMessage);
            if(senderId.toInt() == this->friendId)//打开的窗口和发信息的好友需是同一人
            {
                ui->dialogTextBrowser->append(chatMessage.getTimeAndSender());
                ui->dialogTextBrowser->append(chatMessage.getMessageContent());
                //下面开始打印信息
            }

        }
    });


    connect(ui->messageSendTextEdit, SIGNAL(returnPressed()), this, SLOT(on_btn_send_main_clicked()));
}

MainInterfaceWidget::~MainInterfaceWidget()
{
    delete ui;
}


void MainInterfaceWidget::on_btn_send_main_clicked()
{
    //Sender创建
    UserBrief Sender;
    Sender = {
        userSelf.getUserId(),//id
        userSelf.getUserName(),//username
        "",//photo
        userSelf.getUserGender()//gender
    };
    QDateTime currentTime = QDateTime::currentDateTime(); // 获取当前时间
    int year = currentTime.date().year(); // 获取年份
    int month = currentTime.date().month(); // 获取月份
    int day = currentTime.date().day();     // 获取日期
    int hour = currentTime.time().hour();   // 获取小时
    int minute = currentTime.time().minute(); // 获取分钟
    QString time = QString::number(year) + "-" + QString::number(month) + "-"
            + QString::number(day) + " " + QString::number(hour) + ":" + QString::number(minute);
    //get content
    QString sendContent = ui->messageSendTextEdit->toPlainText();//传输服务器

    //qDebug() << "friendId:" << friendId;
    //connect to server
    //sender信息
    QJsonObject senderValue
    {
        {"id", Sender.id.toInt()},
        {"username", Sender.username},
        {"photo", ""},
        {"gender", Sender.gender.toInt()}
    };
    //receiver信息
    QJsonObject receiverValue
    {
        {"id", friendId},
        {"username", ""},
        {"photo", ""},
        {"gender", 1}
    };
    //发送的信息
    QJsonObject json{
        {"sender",senderValue},
        {"receiver", receiverValue},
        {"time", time},
        {"type", "chat"},
        {"content", sendContent},
        {"is_photo","0"}
    };
    QJsonDocument doc(json);
    QByteArray data = doc.toJson(QJsonDocument::Compact);
    this->socket->sendTextMessage(data);
    Message myMessage {this->friendName, friendId, time, " me:", this->userSelf.getUserId().toInt(), sendContent};
    messageQueue.append(myMessage);
    ui->dialogTextBrowser->append(time + " me:");
    ui->dialogTextBrowser->append("<font color = 'black' size = 24px>" + sendContent + "</font>");
    ui->messageSendTextEdit->clear();
}
void MainInterfaceWidget::on_btn_clear_main_clicked()
{
    ui->messageSendTextEdit->clear();
}

